package LinkedHashSet;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Author 小闽
 * @Date 2024/11/13 17:28
 * @PackageName: LinkedHashSet
 * @ClassName: LinkedHashSetExercise
 * @Description:
 * @Version
 */
@SuppressWarnings({"all"})
public class LinkedHashSetExercise {
    public static void main(String[] args) {
        /**
         * Car类（属性：name，price），如果name和price一样，
         * 就认为是相同的元素，就不能添加
         */
        Set set = new LinkedHashSet();
        set.add(new Car("奥迪",12000));
        set.add(new Car("奥迪",12000));
        set.add(new Car("奔驰",13000));
        set.add(new Car("大众",14000));
        set.add(new Car("本田",16000));

        System.out.println("HashSet= " + set);

    }
}
class Car{
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    // 重写HashCode方法和equals方法

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return Double.compare(car.price, price) == 0 &&
                name.equals(car.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }
}